<template>
  <div class="app-container table-app-container">
    <div class="fixed-table">
      <div class="fixed-table-actionbar">
        <TableFilter :filter="filter" :plan-id="planId" v-bind="$attrs" />
        <ActionBar v-if="!forSelection" :key="planId" :plan-id="planId" :refresh="refresh" v-bind="$attrs" />
      </div>
      <PageableTable
        :loading="loading"
        :data="insideTableData"
        :total="totalElements"
        :page="currentPage"
        :page-size="pageSize"
        :table-height="tableHeight"
        class="fixed-table-table"
        @page-change="onPageChange"
        @sort-change="onSortChange"
        @selection-change="onSelectionChange"
      >
        <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :sortable="column.sortable">
          <template slot-scope="scope">
            <column-render :render="column.render" :row="scope.row" :column="column" />
          </template>
        </el-table-column>
        <el-table-column v-if="!forSelection" label="操作" align="center" width="100" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button v-if="row.status === 'created'" title="编辑" type="text" size="mini" icon="el-icon-edit" @click="edit(row.id)" />
            <!-- <el-button v-if="row.status === 'created'" title="删除" type="text" size="mini" icon="el-icon-delete" @click="remove(row.id)" /> -->
            <el-button v-if="row.status === 'doing'" title="提交" type="text" size="mini" icon="el-icon-success" @click="submit(row.id)" />
            <el-button v-if="managerUsed && !planFinished && row.status === 'finish'" title="驳回" type="text" size="mini" icon="el-icon-close" @click="reject(row)" />
            <el-button title="查看" type="text" size="mini" icon="el-icon-view" @click="view(row.id)" />
            <el-button title="记录" type="text" size="mini" icon="el-icon-notebook-2" @click="viewHistory(row)" />
          </template>
        </el-table-column>
      </PageableTable>
      <FormDialog title="编辑" :show.sync="dialogFormVisible" width="80%" :append-to-body="true" @on-ok="ok" @on-cancel="cancel">
        <EditForm v-if="dialogFormVisible" :id="editId" ref="editForm" :plan-id="planId" :belongs="belongs" />
      </FormDialog>
      <FormDialog title="盘点范围查看" :show.sync="dialogShowScopeVisible" :append-to-body="true" @on-ok="showScopeOk" @on-cancel="showScopeCancel">
        <ShowScopeForm :id="showScopeId" ref="showScopeForm" />
      </FormDialog>
      <ViewDialog
        v-if="dialogForViewResultVisible"
        title="盘点结果"
        :show.sync="dialogForViewResultVisible"
        :append-to-body="true"
        :fullscreen="true"
        width="80%"
        cancel-text="关闭"
        @on-cancel="closeViewResultDialog"
      >
        <InventoryExecuteResult :duty-id="editId" :belongs="belongs" />
      </ViewDialog>
      <ViewDialog
        v-if="dialogHistoryVisible"
        title="任务执行记录"
        :show.sync="dialogHistoryVisible"
        :append-to-body="true"
        width="60%"
        cancel-text="关闭"
        @on-cancel="dialogHistoryVisible=false"
      >
        <History :duty-id="editId" />
      </ViewDialog>
    </div>
  </div>
</template>

<script>
// secondary package based on el-pagination
import FormDialog from '@neu/biz-core/components/FormDialog'
import ViewDialog from '@neu/biz-core/components/ViewDialog'
// 表格查询组件独立编写，需要传递pageable-table实例的mixin方法filter
import TableFilter from './components/tableFilter'
// 编辑实例组件独立编写，需要传递id属性，判断新建还是更新操作
import EditForm from './components/editForm'
import ShowScopeForm from './components/showScopeForm'
// import QrFrom from './components/qrFrom'
import ActionBar from './components/actionBar'
import PageableTable from '@neu/biz-core/components/PageableTable'
import databind from '@neu/biz-core/mixins/databind'
import belongs from '@neu/dcam-ui/mixins/belongs'
import { formatDate } from '@neu/biz-core/utils/utils'
import { getToken } from '@neu/biz-core/utils/auth'
import { INVENTORY_DUTY_STATUS as STATUS, INVENTORY_DUTY_TYPE } from '@neu/dcam-ui/utils/constants'
import {
  page,
  remove,
  enable,
  exportDetail,
  importExcelUrl,
  pageMy,
  reject
} from '@neu/dcam-ui/api/inventoryDuty'
import InventoryExecuteResult from '@neu/dcam-ui/views/inventoryExecuteResult/tables'
import History from './components/history'

export default {
  name: 'InventoryDutyPage',
  components: {
    TableFilter,
    FormDialog,
    EditForm,
    ShowScopeForm,
    ActionBar,
    // QrFrom,
    PageableTable,
    ViewDialog,
    InventoryExecuteResult,
    History
  },
  // 加入混入，使表格混入更多的api操作
  mixins: [databind, belongs],
  props: {
    forSelection: {
      type: Boolean,
      default: false
    },
    status: {
      type: Boolean,
      default: null
    }
  },
  data() {
    return {
      r: page,
      d: remove,
      importUrl: importExcelUrl,
      currRowId: -1,
      insideColumns: [
        { title: '计划编号', key: 'inventoryPlanCode', sortable: 'custom' },
        { title: '计划名称', key: 'inventoryPlanName' },
        { title: '任务名称', key: 'name' },
        { title: '盘点方式', key: 'type', sortable: 'custom',
          render: (h, params) => {
            return h('span', INVENTORY_DUTY_TYPE[params.row.type])
          }
        },
        { title: '责任人', key: 'userName' },
        { title: '更新时间', key: 'updateTime', sortable: 'custom', render: (h, params) => { return h('span', formatDate(params.row.updateTime)) } },
        { title: '状态', key: 'status', sortable: 'custom',
          render: (h, params) => {
            return h('span', [
              h('el-tag', STATUS[params.row.status])
            ])
          }
        }
      ],
      dialogFormVisible: false,
      dialogShowScopeVisible: false,
      editId: -1,
      showScopeId: -1,
      planId: -1,
      // 任务状 态
      inventoryDutyStatus: [],
      // 二维码参数
      qrId: -1,
      // 二维码弹窗
      dialogQrFormVisible: false,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      },
      dialogForViewResultVisible: false,
      INVENTORY_DUTY_TYPE,
      dialogHistoryVisible: false,
      managerUsed: false,
      planFinished: true
    }
  },
  created() {
    this.planId = this.$route.query.planId ? Number(this.$route.query.planId) : (this.$attrs['plan-id'] ? this.$attrs['plan-id'] : -1)
    const searchObj = {}
    if (this.planId > -1) {
      searchObj['s_planId'] = this.planId
      this.managerUsed = true
    } else {
      this.r = pageMy
      this.managerUsed = false
    }
    this.filter(searchObj)
  },
  methods: {
    responseFormatter: function(i) {
      if (i.length > 0) {
        this.planFinished = i[0].inventoryPlanStatus === 'finish'
      }
      return i
    },
    // 表格编辑按钮点击事件处理
    edit(id) {
      // 打开对话框
      this.dialogFormVisible = true
      // 更新当前被编辑实体的ID，自动传递至编辑表单
      this.editId = id
    },
    showScope(id) {
      // 打开对话框
      this.dialogShowScopeVisible = true
      // 更新当前被编辑实体的ID，自动传递至编辑表单
      this.showScopeId = id
    },
    // 编辑资产对话框确认事件处理
    ok() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // 直接调用表单实例的保存方法
      this.$refs.editForm.save().then(response => {
        loading.close()
        if (response === false) return
        this.$message({
          showClose: true,
          message: '操作成功！',
          type: 'success'
        })
        // 调用pageable-table实例的mixin方法refresh()，更新表格
        this.refresh()
        // 关闭对话框
        this.dialogFormVisible = false
        this.dialogShowScopeVisible = false
      })
    },
    cancel() {
      this.editId = -1
      this.$refs.editForm.reset()
      // 关闭对话框
      this.dialogFormVisible = false
      this.dialogShowScopeVisible = false
    },
    // 打开二维码的界面
    qrCodeDialog(id) {
      this.qrId = id
      this.dialogQrFormVisible = true
    },
    // 二维码弹窗确定
    qrOk() {
      this.$message({
        showClose: true,
        message: '暂不支持下载,等待开发！',
        type: 'waring'
      })
      // this.dialogQrFormVisible = false
    },
    showScopeOk() {
      this.showScopeId = -1
      this.dialogShowScopeVisible = false
    },
    // 二维码弹窗取消
    qrCancel() {
      this.dialogQrFormVisible = false
    },
    showScopeCancel() {
      this.showScopeId = -1
      this.dialogShowScopeVisible = false
    },
    // 任务完成
    toEnable(id, flag) {
      this.$confirm('任务确定完成了?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        enable(id, flag).then(response => {
          this.$message({
            type: 'success',
            message: '确认成功!'
          })
          this.refresh()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消确定'
        })
      })
    },
    // 任务确认
    toConfirm(id, flag) {
      this.$confirm('确认任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        enable(id, flag).then(response => {
          this.$message({
            type: 'success',
            message: '确认成功!'
          })
          this.refresh()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消确定'
        })
      })
    },
    // 跳转详细页面
    toResult(id, status) {
      const query = {
        'dutyId': id,
        'status': status,
        ...this.$route.query
      }
      this.$router.push({ name: 'dcam_inventoryResult', query: query })
    },
    // 导出详情
    toDownload(id) {
      exportDetail(id).then(res => {
        const content = res.data
        const blob = new Blob([content])
        const fileName = '盘点详细.xlsx'
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    handleBeforeUpLoad(file) {
      if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        this.$message({
          showClose: true,
          message: '文件 ' + file.name + ' 格式不正确，请上传.xls,.xlsx文件。',
          type: 'error'
        })
      }
    },
    handleSuccess(response, file, fileList) {
      if (response.status === 'failure') {
        this.$message({
          showClose: true,
          message: response.data,
          type: 'error'
        })
      } else {
        this.$message({
          showClose: true,
          message: '文件上传成功',
          type: 'success'
        })
        this.refresh()
      }
    },
    handleError() { },
    action() {
      return this.importUrl + '/' + this.currRowId
    },
    // 查看盘点结果
    view(id) {
      this.editId = id
      this.dialogForViewResultVisible = true
    },
    closeViewResultDialog() {
      this.dialogForViewResultVisible = false
    },
    submit(id) {
      this.$confirm('确定要提交该任务？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        enable(id, 'finish').then(response => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.refresh()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消完成'
        })
      })
    },
    viewHistory(row) {
      this.editId = row.id
      this.dialogHistoryVisible = true
    },
    reject(row) {
      this.$prompt('请输入驳回原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        reject(row.id, value).then(response => {
          this.$message({
            type: 'success',
            message: '盘点任务已驳回'
          })
          this.refresh()
        })
      }).catch(() => {
      })
    }
  }
}
</script>
